package gao.xiaolei.controller;

import gao.xiaolei.entity.ResponseEnvelope;
import gao.xiaolei.service.TimeSheetService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.*;
import gao.xiaolei.exception.CheckOnWorkException;

import javax.annotation.Resource;

@RestController
@RequestMapping("/checkOnWork")
public class TimeSheetController {

    @Resource(name = "TimeSheetService")
    private TimeSheetService timeSheetService;

    //在某个项目打卡
    @PostMapping("")
    public Integer checkOoWorkOnProject(@RequestParam("userId")String userId,
                                        @RequestParam("projectId")String projectId){
        return timeSheetService.checkOoWorkOnProject(userId,projectId);
    }

    //获取某个项目某人今天打卡的次数
    @GetMapping("/{projectId}/{userId}")
    public Integer getTodayCheckTime(@PathVariable("userId")String userId,
                            @PathVariable("projectId")String projectId){
        return timeSheetService.getCheckTimeToday(userId,projectId);
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<ResponseEnvelope<String>> handelError(Exception e) {
        e.printStackTrace();
        Integer code = null;
        if (e.getClass() == MissingServletRequestParameterException.class)
            code = 400;
        else if (e.getClass() == CheckOnWorkException.class)
            code = 408;
        else
            code = 500;
        ResponseEnvelope<String> result = new ResponseEnvelope<String>(code, e.getMessage(), null);
        return new ResponseEntity<ResponseEnvelope<String>>(result, HttpStatus.valueOf(500));
    }
}
